package com.ze.java.concurrent;

/**
 * 三个线程顺序输出ABC
 * @Author:yangzy
 * @Date:2021/4/2 9:42
 */
public class PrintAbc {

    public static void main(String[] args) {
        Object a = new Object();
        Object b = new Object();
        Object c = new Object();

        Thread threadA = new PrintThread("A", c, a);
        threadA.start();
        Thread threadB = new PrintThread("B", a, b);
        threadB.start();
        Thread threadC = new PrintThread("C", b, c);
        threadC.start();
    }

    static class PrintThread extends Thread {
        int count = 10;
        Object prev;
        Object self;
        String printText;

        public PrintThread(String printText, Object prev, Object self) {
            this.prev = prev;
            this.self = self;
            this.printText = printText;
        }

        @Override
        public void run() {
            while (count > 0) {
                synchronized (prev) {
                    synchronized (self) {
                        System.out.print(printText);
                        count--;
                        self.notify();
                    }
                    try {
                        prev.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
